package com.sky.controller.admin.User;

import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录操作
     * */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) throws Exception {
        log.info("员工登录code：{}",userLoginDTO);
        ///
        User user =  userService.userInfoReturn(userLoginDTO);
        /// 创建map对象
        Map claims = new HashMap();
        // 放入用户唯一标识
        claims.put("userId",user.getId());
        /// jwt令牌,UserTtl是过期时间,2 hours
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),claims);
        /// 给userLoginVO传入值
        UserLoginVO userLoginVO = UserLoginVO.builder().id(user.getId())
                .token(token).openid(user.getOpenid()).build();
        /// 设置完后返回userLoginVO里面有token，openid，id
        return Result.success(userLoginVO);
    }

}
